package io.zt.dangyuan;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import io.zt.dangyuan.customView.OnRefreshListener;
import io.zt.dangyuan.customView.RefreshListView;
import io.zt.dangyuan.object.CommotListObject;
import io.zt.dangyuan.object.CommotRequest;
import com.orhanobut.logger.Logger;

import org.xutils.ex.HttpException;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

import butterknife.ButterKnife;
import butterknife.InjectView;

public class BBSCommentActivity extends BaseActivity implements OnRefreshListener {
    @InjectView(R.id.feedback_submit)
    TextView feedbackSubmit;
    @InjectView(R.id.feedback_content)
    EditText feedbackContent;
    @InjectView(R.id.activity_read_love_listview)
    RefreshListView commentList;
    private int type;
    private CommotRequest commotRequest;
    private BBSCommetAdapter bbsCommetAdapter;
    private int contentid;
    private CommotListObject  commotListObject;
    List<CommotListObject.ListEntity> lists;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addCenterView(R.layout.activity_comment_list);
        ButterKnife.inject(this);
        toolbar.setNavigationIcon(R.drawable.icon_pre);
        lists = new ArrayList<CommotListObject.ListEntity>();
        commotRequest = new CommotRequest();
        commotRequest.setPageSize(10+"");
        commotRequest.setTapType("1");
        initData();
        webRequst(true);
    }

    private void initData() {
        Intent intent = getIntent();
        type = intent.getIntExtra("type", BBSDetailActivity.TYPE_ZHONGCHOU);
        contentid = intent.getIntExtra("contentid", BBSDetailActivity.TYPE_ZHONGCHOU);
        switch (type) {
            case BBSDetailActivity.TYPE_COMMENT:
                setTitle("评论列表");
                feedbackSubmit.setText("评论");
                feedbackContent.setHint("输入评论内容");
                break;
            case BBSDetailActivity.TYPE_BAOMING:
                setTitle("报名列表");
                feedbackSubmit.setText("报名");
                feedbackContent.setHint("输入留言内容");
                break;
            case BBSDetailActivity.TYPE_ZHONGCHOU:
                setTitle("众筹列表");
                feedbackSubmit.setText("参与众筹");
                feedbackContent.setHint("输入众筹留言内容");
                break;
        }

        bbsCommetAdapter = new BBSCommetAdapter(this,lists);
        commentList.setAdapter(bbsCommetAdapter);
        commentList.setOnRefreshListener(this);
        commentList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            }
        });
        feedbackSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                webSendRequst();
//                invalidateOptionsMenu();
            }
        });



    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
        }

        return true;
    }

    public Boolean check() {
        if (TextUtils.isEmpty(feedbackContent.getText())) {

            String str = null;
            switch (type) {
                case BBSDetailActivity.TYPE_COMMENT:
                    str = "评论";

                    break;
                case BBSDetailActivity.TYPE_BAOMING:
                    str = "报名";

                    break;
                case BBSDetailActivity.TYPE_ZHONGCHOU:
                    str = "众筹";
                    break;
            }

            Toast.makeText(this, str + "内容不能为空", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    public void webRequst(boolean ishow) {
        HashMap<String,Object> map = new HashMap<String,Object>();
        if (commotRequest.getTapType().equals("1")) {
           // map.put("criticalId", contentListRequest.getArcType());
        } else if (commotRequest.getTapType().equals("2")){
            CommotListObject.ListEntity object  =  lists.get(lists.size() - 1);
            map.put("criticalid", UUID.randomUUID().toString());
        }

        map.put("contentid", String.valueOf(contentid));
       // map.put("taptype", feedbackContent.getText().toString());
        map.put("taptype",commotRequest.getTapType());
        //map.put("pagesize", ""+commotRequest.getPageSize());
        map.put("pagesize", "10");
        WebUtils.showProgress = ishow;
        WebUtils.sendPost(BBSCommentActivity.this, "commentList", map, new WebUtils.OnWebListenr() {
            @Override
            public void onSuccess(boolean isSuccess, String msg, String data) {
                commotListObject = JSON.parseObject(data, CommotListObject.class);
                lists.addAll(commotListObject.getList());
                if (commotListObject.getCount() == 0) {
                   // noDataView.setVisibility(View.VISIBLE);
                } else {
                    bbsCommetAdapter.notifyDataSetChanged();
                        noDataView.setVisibility(View.GONE);
                }


            }

            @Override
            public void onFailed(HttpException error, String msg) {

            }
        });

    }

    public void webSendRequst() {

        boolean isgo = check();
        if (!isgo) {
            return;
        }
        final GlobalDataApplication app = (GlobalDataApplication) getApplication();

        if (app.getUserModel() == null)
        {
            startActivity(new Intent(BBSCommentActivity.this, LoginActivity.class));
            return;
        }else
        {

        }

        String conmentStr="";
        try {
            conmentStr=   URLEncoder.encode(feedbackContent.getText().toString(), "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        HashMap<String,Object> map = new HashMap<String,Object>();

        map.put("contentid", String.valueOf(contentid));
        map.put("text", conmentStr);
        map.put("userid", String.valueOf(app.getUserModel().getUserid()));

        WebUtils.sendPost(BBSCommentActivity.this, "comment", map, new WebUtils.OnWebListenr() {
            @Override
            public void onSuccess(boolean isSuccess, String msg, String data) {

                if (isSuccess) {
                   Toast.makeText(BBSCommentActivity.this, "评论成功", Toast.LENGTH_SHORT).show();
                    /// 评论完成
                    feedbackContent.setText("");
                    lists.clear();
                    webRequst(true);
               Logger.e("bbc","我在评论");
                }else
                {
                    Toast.makeText(BBSCommentActivity.this, msg, Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailed(HttpException error, String msg) {

            }
        });


    }

    @Override
    public void onDownPullRefresh() {
        new AsyncTask<Void, Void, Void>() {

            @Override
            protected Void doInBackground(Void... params) {
                lists.clear();
                commotRequest.setTapType("1");
                webRequst(false);
                return null;
            }

            @Override
            protected void onPostExecute(Void result) {
                commentList.hideHeaderView();
            }
        }.execute(new Void[]{});
    }

    @Override
    public void onLoadingMore() {
        new AsyncTask<Void, Void, Void>() {

            @Override
            protected Void doInBackground(Void... params) {
               // commotRequest.setPageSize(commotRequest.getPageSize()+5);
                commotRequest.setTapType("2");
                webRequst(false);
//                if (readLoveRequest.isHasMoreData()) {
//                    readLoveRequest.setCurrpage(readLoveRequest.getCurrpage() + 1);
//                    webRequst();
//                } else {
//                    h.sendEmptyMessage(0);
//                }
                return null;
            }
            @Override
            protected void onPostExecute(Void result) {
                // 控制脚布局隐藏
                commentList.hideFooterView();
            }
        }.execute(new Void[]{});
    }
}
